<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>部门管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="icon" href="${pageContext.request.contextPath}/lib/static/login/images/favicon.ico">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/lib/layui/css/layui.css" media="all">
    <script src="${pageContext.request.contextPath}/lib/static/common/js/jquery.min.js"></script>
    <script src="${pageContext.request.contextPath}/lib/static/common/js/jquery.form.js"></script>
    <script src="${pageContext.request.contextPath}/lib/layui/layui.js" charset="utf-8"></script>
</head>
<body>
<div class="layui-fluid">
    <div class="layui-row">
        <fieldset class="layui-elem-field layui-field-title">
            <legend>部门管理</legend>
        </fieldset>
    </div>
    <hr class="layui-bg-red">

    <!--按钮及查询框组-->
    <div class="layui-row">
        <%--<div class="layui-col-md-offset8">--%>
        <div class="layui-col-md-offset1">
            <form class="layui-form">
                <div class="layui-inline">
                    <input class="layui-input" name="criteria" autocomplete="off" placeholder="部门名称/部门详情">
                </div>
                <button class="layui-btn layuiadmin-btn-admin" lay-submit="" lay-filter="search">
                    <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                </button>
            </form>
        </div>
    </div>

    <table class="layui-hide" id="departmentTable" lay-filter="departmentMonitor"></table>

    <script type="text/html" id="departmentToolbar">
        <div class="layui-btn-container">
            <%--<button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
            <button class="layui-btn layui-btn-sm" lay-event="refresh"
                    onclick="window.location.href='${pageContext.request.contextPath}/sys/department/department_ui';">刷新
            </button>
            <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
            <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>--%>
            <button class="layui-btn layui-btn-sm" lay-event="delAll">删除</button>
            <button class="layui-btn layui-btn-sm" lay-event="add">新增</button>
        </div>
    </script>

    <script type="text/html" id="departmentBar">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <script>
        var baseUrl = '${pageContext.request.contextPath}/sys/department/';
        /*发送ajax请求访问后台*/
        function sendAjaxPostReq($, param, tableDept, method) {
            $.post(
                baseUrl + method,
                param,
                function (result) {
                    if (result.code == 0) {
                        layer.msg(result.msg, {icon: 1});
                        /*刷新表格数据*/
                        tableDept.reload({
                            url: baseUrl + "get"
                        });
                    } else {
                        layer.msg(result.msg, {icon: 5});
                    }
                },
                "json"
            );
        }

        /*公用根据id或ids删除用户*/
        function deleteUserByIds($, ids, tableDept, data) {
            /*if (len == 0) {
                layer.msg("请先选中记录", {icon: 5});
            }*/
            /*多项删除时没有选择数据时给出提示*/
            var params = {"id": ids}
            var len = data.length;
            if (len < 1) {
                layer.alert('请至少选择一条您要删除的数据', {
                    skin: 'layui-layer-molv'
                    , closeBtn: 0
                });
                return;
            }else if(len>1) {
                layer.confirm("您选中了" + len + "条数据，确认删除？", function (index) {
                    /*发送ajax请求访问后台*/
                    sendAjaxPostReq($, params, tableDept, "deleteByIds");
                    layer.close(index);
                });
            }else{
                layer.confirm("确定删除吗？", function (index) {
                    /*发送ajax请求访问后台*/
                    sendAjaxPostReq($, params, tableDept, "deleteByIds");
                    layer.close(index);
                });
            }
        }

        layui.use(['jquery', 'table', 'form'], function () {
            var $ = layui.$;
            var table = layui.table;
            var form = layui.form;
            /*数据表格*/
            var tableDept = table.render({
                elem: '#departmentTable'
                , title: '用户数据'
                , toolbar: '#departmentToolbar'
                , defaultToolbar: ['filter']
                , url: baseUrl + 'get'
                ,height: 'full-150'
                //,totalRow: true	  //合计行
                , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                , cols: [[{type: 'checkbox', fixed: 'left'}
                    , {field: 'id', title: 'ID', sort: true, align: 'center', width: 70, totalRowText: '合计'}
                    , {field: 'deptName', title: '部门名称', align: 'center', totalRow: true} //width 支持：数字、百分比和不填写。你还可以通过 minWidth 参数局部定义当前单元格的最小宽度，layui 2.2.1 新增
                    /*, {field: 'superDeptName', title: '上级部门', align: 'center'}*/
                    , {field: 'deptDesc', title: '部门详情', align: 'center'}
                    , {
                        field: 'addTime',
                        title: '添加时间',
                        sort: true,
                        align: 'center',
                        templet: '<div>{{layui.laytpl.toDateString(d.addTime)}}</div>'
                    }
                    , {field: 'addUser', title: '创建人', align: 'center'}
                    , {
                        field: 'updateTime',
                        title: '修改时间',
                        sort: true,
                        align: 'center',
                        templet: '<div>{{layui.laytpl.toDateString(d.updateTime)}}</div>'
                    }
                    , {field: 'updateUser', title: '修改人', align: 'center'}
                    /*, {field: 'remark', title: '操作备注', align: 'center'}*/
                    /*, {field: 'isdel', title: '状态', sort: true, align: 'center', width: 115}*/
                    , {fixed: 'right', title: '操作', toolbar: '#departmentBar', width: 115, align: 'center'}
                ]]
                , request: {
                    pageName: 'pageNo' //页码的参数名称，默认：page
                    , limitName: 'pageSize' //每页数据量的参数名，默认：limit
                }
                , page: {
                    layout: ['limit', 'count', 'prev', 'page', 'next', 'skip']
                    , groups: 5
                }
            });

            //时间戳处理
            layui.laytpl.toDateString = function (d, format) {
                var date = new Date(d || new Date())
                    , ymd = [
                    this.digit(date.getFullYear(), 4)
                    , this.digit(date.getMonth() + 1)
                    , this.digit(date.getDate())
                ]
                    , hms = [
                    this.digit(date.getHours())
                    , this.digit(date.getMinutes())
                    , this.digit(date.getSeconds())
                ];
                format = format || 'yyyy-MM-dd HH:mm:ss';
                return format.replace(/yyyy/g, ymd[0])
                    .replace(/MM/g, ymd[1])
                    .replace(/dd/g, ymd[2])
                    .replace(/HH/g, hms[0])
                    .replace(/mm/g, hms[1])
                    .replace(/ss/g, hms[2])
            };
            //数字前置补零
            layui.laytpl.digit = function (num, length, end) {
                var str = '';
                num = String(num);
                length = length || 2;
                for (var i = num.length; i < length; i++) {
                    str += '0';
                }
                return num < Math.pow(10, length) ? str + (num | 0) : num;
            };

            //头工具栏事件，添加和多个删除
            table.on('toolbar(departmentMonitor)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id);
                switch (obj.event) {
                    case 'getCheckData':
                        var data = checkStatus.data;
                        layer.alert(JSON.stringify(data));
                        break;
                    case 'getCheckLength':
                        var data = checkStatus.data;
                        layer.msg('选中了：' + data.length + ' 个');
                        break;
                    case 'isAll':
                        layer.msg(checkStatus.isAll ? '全选' : '未全选');
                        break;
                    case 'delAll':
                        /*获得要删除的ids*/
                        var data = checkStatus.data;
                        var ids = [];
                        $.each(data, function (index, value) {
                            var id = value.id;
                            ids.push(id);
                        });
                        /*根据id删除数据*/
                        deleteUserByIds($, ids.toString(), tableDept, data);
                        break;
                    case 'add':
                        layer.open({
                            content: [baseUrl + 'department_add'],
                            type: 2,
                            title: '<h2>添加部门</h2>',
                            maxmin: true,
                            shadeClose: true, //点击遮罩关闭层
                            offset: '100px',
                            area: ['400px', '520px'],
                            success: function (layero, index) {
                                layer.iframeAuto(index);
                            }
                        });
                        break;
                };
            });

            //监听行工具事件,编辑和删除操作
            table.on('tool(departmentMonitor)', function (obj) {
                var data = obj.data
                if (obj.event === 'del') {
                    /*根据id删除数据*/
                    deleteUserByIds($, data.id, tableDept, data);
                    layer.close(index);
                } else if (obj.event === 'edit') {
                    layer.open({
                        content: [baseUrl + 'department_edit'],
                        type: 2,
                        title: '<h2>修改部门信息</h2>',
                        maxmin: true,
                        shadeClose: true, //点击遮罩关闭层
                        offset: '100px',
                        area: ['400px', '520px'],
                        success: function (layero, index) {
                            var body = layer.getChildFrame('body', index);  //获取到子页面的内容
                            body.find("input[name='deptName']").val(data.deptName);
                            body.find("textarea[name='deptDesc']").val(data.deptDesc);
                            body.find("input[name='id']").val(data.id);
                            body.find("#superId").val(data.superDeptId);
                            layer.iframeAuto(index);
                        },
                    });
                }
            });

            /* 查询 */
            form.on('submit(search)', function (data) {
                tableDept.reload({
                    url: "get"
                    , method: "post" /*解决参数传递中文乱码*/
                    , where: data.field
                });
                return false;
            });
        });
    </script>
</div>
</body>
</html>
